package org.itboys.rpc.service.sms;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.itboys.ResultHolder;
import org.itboys.commons.utils.random.RandomUtils;
import org.itboys.commons.utils.sms.SmsUtils;
import org.itboys.constant.ErrorConstant;
import org.itboys.dto.base.Result;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.rpc.constant.RpcConstant;
import org.itboys.rpc.entity.ValidateCode;
import org.springframework.stereotype.Service;

import org.mongodb.morphia.query.Query;

/**
 * 短信验证码相关
 * @author weisky
 *
 */
@Service
public class ValidateCodeService extends BaseService<ValidateCode, Long>{
	
	private static final long serialVersionUID = 1L;
	
	@Resource(name = "baseMongoDS")
	private MongoDataSource ds;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<ValidateCode> getEntityClass() {
		return ValidateCode.class;
	}

	/**
	 * 新增
	 * @param validateCode
	 * @return
	 */
	public boolean insert(ValidateCode validateCode){
		try{
			super.save(validateCode);
			logger.info("新增验证码成功：mobile={}, code={}, type={}", new Object[]{validateCode.getMobile(), validateCode.getCode(), validateCode.getType()});
			return true;
		}catch(Exception e){
			logger.error("ValidateCodeService.insert error: mobile="+validateCode.getMobile()+",code="+validateCode.getCode()+",type="+validateCode.getType(), e);
			return false;
		}
	}
	
	/**
	 * 获取注册用的验证码
	 * 这里没有设置有效时间
	 * @param mobile
	 * @return
	 */
	public String getCodeReg(String mobile){
		if(StringUtils.isBlank(mobile)){//手机号为空
			return null;
		}
		Query<ValidateCode> query = getMongoDataSource().createQuery(getEntityClass())
				.field("mobile").equal(mobile)
				.field("type").equal(RpcConstant.VALIDATE_CODE_REG)
				.order("-ct");
		List<ValidateCode> list = query.asList();
		return (!list.isEmpty()) ? list.get(0).getCode() : null;
	}
	
	/**
	 * 获取忘记密码时的验证码
	 * @param mobile
	 * @return
	 */
	public String getCodeForgetPwd(String mobile){
		if(StringUtils.isBlank(mobile)){//手机号为空
			return null;
		}
		Query<ValidateCode> query = getMongoDataSource().createQuery(getEntityClass())
				.field("mobile").equal(mobile)
				.field("type").equal(RpcConstant.VALIDATE_CODE_FORGET_PWD)
				.order("-ct");
		List<ValidateCode> list = query.asList();
		return (!list.isEmpty()) ? list.get(0).getCode() : null;
	}
	
	/**
	 * 获取修改密码时的验证码
	 * @param mobile
	 * @return
	 */
	public String getCodeUpdPwd(String mobile){
		if(StringUtils.isBlank(mobile)){//手机号为空
			return null;
		}
		Query<ValidateCode> query = getMongoDataSource().createQuery(getEntityClass())
				.field("mobile").equal(mobile)
				.field("type").equal(RpcConstant.VALIDATE_CODE_UPD_PWD)
				.order("-ct");
		List<ValidateCode> list = query.asList();
		return (!list.isEmpty()) ? list.get(0).getCode() : null;
	}
	
	/**
	 * 发送验证码
	 * @param mobile
	 * @param type
	 * @return
	 */
	public Result<Void> sendValidateCode(String mobile, int type){
		String content = null;
		try{
			int code = RandomUtils.buildRandom(6);//生成6位的随机数
			content = RpcConstant.VALIDATE_CODE_CONTENT.replaceAll("@code", String.valueOf(code));
			
			ValidateCode validateCode = new ValidateCode();
			validateCode.setCode(String.valueOf(code));
			validateCode.setMobile(mobile);
			validateCode.setType(type);
			boolean resu = insert(validateCode);
			
			if(!resu){//插入失败
				return ResultHolder.getFailResult(ErrorConstant.ACTION_FAIL, "验证码生成失败");
			}
			
			boolean result = SmsUtils.send(mobile, content);
			if(result){//发送成功
				logger.info("验证码发送成功：mobile={},content={},type={}", new Object[]{mobile, content, type});
				return ResultHolder.getSuccessResult(null);
			}else{//发送失败
				return ResultHolder.getFailResult(ErrorConstant.ACTION_FAIL, "验证码发送失败");
			}
		}catch(Exception e){
			logger.error("ValidateCodeService.sendValidateCode 验证码发送失败:mobile="+mobile+",content="+content+",type="+type, e);
			return ResultHolder.getExceptionResult();
		}
	}
	
}

